public class TreeNodeConvertToListNode {

    public static void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        flatten(root.left);
        flatten(root.right);

        //先将左右节点都展开
        TreeNode left = root.left; //3
        //保存当前节点的 右节点
        TreeNode right = root.right;  //4
        //将左节点置空，右节点转化为左节点
        root.left = null;
        root.right = left;        //2->3
        //        遍历当前节点的右节点找到最后一个节点 3
        //        2             2
        //     3     4             3
        TreeNode resultNode = root;
        while (resultNode.right != null) {
            resultNode = resultNode.right;
        }
        //      将右子树接到左子树的下方  2->3->4
        resultNode.right = right;
    }
    public static void flatten_new(TreeNode root) {
       if(root == null) return;

       flatten_new(root.left);
       flatten_new(root.right);

       TreeNode left = root.left;
       TreeNode right = root.right;

       root.left = null;
       root.right = left;

       TreeNode resultTreeNode = root;
       while(resultTreeNode.right!=null){
           resultTreeNode = resultTreeNode.right;
       }
        resultTreeNode.right = right;

        System.out.println(resultTreeNode.toString());
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(2);
        TreeNode left = new TreeNode(3);
        TreeNode right = new TreeNode(4);
        root.left = left;
        root.right = right;
//        System.out.println(root.toString());
        flatten_new(root);
//        System.out.println(root.toString());
    }
}
